using System;
using System.Linq.Expressions;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using FluentSilverlight.Utility.Reflection;

namespace FluentSilverlight.Expressions.Buttons
{
    public abstract class ToggleButtonExpression<THIS, TModel, VIEW> : ButtonBaseExpression<THIS, TModel, VIEW> 
        where THIS : ToggleButtonExpression<THIS, TModel, VIEW>
        where TModel : class 
        where VIEW : ToggleButton
    {
        private bool isThreeState;
        private bool? isChecked = false;
        private Expression<Func<TModel, object>> isCheckedExpression;
        protected BindingMode isCheckedBindingMode = BindingMode.OneTime;

        protected ToggleButtonExpression(TModel model) : base(model)
        {
        }

        protected ToggleButtonExpression(TModel model, string name) : base(model, name)
        {
        }

        public THIS IsChecked(bool? value)
        {
            isChecked = value;
            return thisInstance();
        }

        public THIS IsChecked(Expression<Func<TModel, object>> expression)
        {
            isCheckedExpression = expression;
            return thisInstance();
        }

        public THIS IsChecked(Expression<Func<TModel, object>> expression, BindingMode bindingMode)
        {
            isCheckedExpression = expression;
            isCheckedBindingMode = bindingMode;
            return thisInstance();
        }

        public THIS IsThreeState(bool value)
        {
            isThreeState = value;
            return thisInstance();
        }

        protected override void BuildUp(VIEW item)
        {
            base.BuildUp(item);
            
            if(isCheckedExpression != null)
            {
                var accessor = ReflectionHelper.GetAccessor(isCheckedExpression);
                var binding = new Binding(accessor.Name) { Mode = isCheckedBindingMode };

                item.SetBinding(ToggleButton.IsCheckedProperty, binding);
            }
            else
                item.IsChecked = isChecked;

            item.IsThreeState = isThreeState;
        }
    }
}